package com.skyline.courier.net.provider.kryo;

import java.io.ByteArrayInputStream;
import java.util.Arrays;
import java.util.List;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Registration;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.skyline.courier.net.Serializer;

/**
 * Kryo的序列化和反序列化实现类
 * 
 * @author wuqh
 * 
 */
public class KryoSerializer implements Serializer {

	private Kryo kryo;
	/**
	 * 初始容量0.5K
	 */
	private int initialCapacity = 512;
	/**
	 * 最大容量5M
	 */
	private int maxCapacity = 5 * 1024 * 1024;

	private List<Class<?>> registeredClass;

	public KryoSerializer() {
		this.kryo = new Kryo();
	}

	public void init() throws ClassNotFoundException {
		if (registeredClass != null) {
			for (Class<?> clazz : registeredClass) {
				register(clazz);
			}
		}
	}

	public Registration register(Class<?> type, com.esotericsoftware.kryo.Serializer<?> serializer) {
		return kryo.register(type, serializer);
	}

	public void register(Class<?> clazz) {
		kryo.register(clazz);
	}

	public byte[] serialize(Object object) {
		Output output = new Output(initialCapacity, maxCapacity);
		kryo.writeClassAndObject(output, object);
		return output.toBytes();
	}

	public Object deserialize(byte[] bytes) throws Exception {
		Input input = new Input(new ByteArrayInputStream(bytes));
		return kryo.readClassAndObject(input);
	}

	public void setRegisteredClass(List<Class<?>> registeredClass) {
		this.registeredClass = registeredClass;
	}

	public void setRegisteredClass(Class<?>... registeredClass) {
		if (registeredClass != null) {
			this.registeredClass = Arrays.asList(registeredClass);
		}
	}

	public void setRegistrationRequired(boolean registrationRequired) {
		kryo.setRegistrationRequired(registrationRequired);
	}

	public void setInitialCapacity(int initialCapacity) {
		this.initialCapacity = initialCapacity;
	}

	public void setMaxCapacity(int maxCapacity) {
		this.maxCapacity = maxCapacity;
	}

	/**
	 * public static void main(String... args) throws Exception { Message o =
	 * new Message(); o.setArgs(new Object[] { "啊渐叟i爱多久啊", "安静搜大酒店", "阿萨大大大大"
	 * }); byte[] bs = (new KryoSerializer()).serialize(o);
	 * System.out.println(new String(bs)); Message m = (Message) (new
	 * KryoSerializer()).deserialize(bs); System.out.println(m); }
	 * 
	 * public static class Message { private String id; private Object[] args;
	 * 
	 * public void setArgs(Object[] args) { this.args = args; }
	 * 
	 * public void setId(String id) { this.id = id; }
	 * 
	 * public String toString() { String s = "id:" + id + ",args:["; for (Object
	 * arg : args) { s = s + arg.toString() + ","; } s = s + "]";
	 * 
	 * return s; } }
	 */
}
